import React, { Component } from 'react'
import './index.css';
// import Header from '../Header';
// import Main from '../Main';
// import Footer from '../Footer';
// import{nanoid} from 'nanoid'
import axios from 'axios';
export default class App extends Component {

    state = {
        duanzi: [
        ],
        author: '',
        content: ''
    }
    render () {
        return <div>{/*左侧表单区start*/}
            {/*左侧表单区start*/}
            <div className='left'>
            作者<input type="text" value ={this.state.author} /><br />
            内容<br/><textarea value ={this.state.content} cols="30" rows="10"></textarea><br />
            </div>
            {/*左侧表单区end*/}
            {/*右侧表单区start*/}
            <div className='right'>
                <h2>段子列表</h2>
                <table border="1">
                    <thead>
                        <tr><td>ID</td><td>作者</td><td>段子内容</td><td width="80">操作</td></tr>
                    </thead>
                    <tbody>
                        {
                            this.state.duanzi.map(item => {
                                return <tr key={item.id}>
                                    <td>{item.id}</td>
                                    <td>{item.name}</td>
                                    <td>{item.text}</td>
                                    <td><button did={item.id} onClick={this.removeDuanzi}>点击删除</button></td>
                                </tr>
                            })
                        }
                    </tbody>
                </table>
            </div >
        </div>
         {/*右侧表单区end*/}
    }
    removeDuanzi = async (e) => {
        if (!window.confirm('您确定要删除该段子么')) return;
        // 删除服务端的那一条段子  restful API     GET 获取 POST 新增  PATCH  PUT  更新  DELETE 删除数据
        //获取对应的 id
        let id = e.target.getAttribute('did');
        let result = await axios({
            method: 'delete',
            url: 'http://127.0.0.1:3002/duanzi/' + id
        });
        //更新页面的显示
        this.setState({
            duanzi: this.state.duanzi.filter(item => item.id !== Number(id))
        })
    }
    async componentDidMount () {
        let { data } = await axios.get('http://127.0.0.1:3002/duanzi')
        console.log(data);
        //设置 state 中段子属性的值
        this.setState({
            duanzi: data
        })
    }
}
